<?php

namespace app\admin\controller;
use app\common\model\Config as ConfigModel;
use app\common\controller\Backend;
use think\Db;
use think\Session;

/**
 * 酒店管理
 *
 * @icon   fa fa-list
 * @remark 用于统一管理网站的所有分类,分类可进行无限级分类,分类类型请在常规管理->系统配置->字典配置中添加
 */
class Closeroom extends Backend
{

    protected $hid = null;
    protected $adminId = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->hid = Session::get("admin")["hotelid"];
        $this->adminId = Session::get("admin")["id"];
        $hotels = db("hotels")->where("h_status = 'normal'")->select();
        $this->assign("hotels",$hotels);
    }

    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $search = $this->request->request("search");
            $search = trim($search);

            $model = model('closeroom');
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();


            if($this->adminId == 1){
                $total = $model->where('chtitle','like','%'.$search.'%')->order($sort, $order)->group("chid")->count();
                $list = $model
                    ->order($sort, $order)
                    ->where('chtitle','like','%'.$search.'%')
                    ->group("chid")
                    ->limit($offset, $limit)
                    ->select();
            }else{
                $total = $model->where("chid",'in',$this->hid)->where('chtitle','like','%'.$search.'%')->order($sort, $order)->count();
                $list = $model
                    ->where("chid",'in',$this->hid)
                    ->where('chtitle','like','%'.$search.'%')
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }

            foreach ($list as &$v){
                $hid = $v['chid'];
                $count = $model->where(['chid'=>$hid])->count();
                $v['count'] = $count;
            }


            $result = array("total" => $total, "rows" => $list);

            return json($result);

        }
        return $this->view->fetch();
    }

    /**
     * 批量更新
     */
    public function multi($ids = "")
    {

        $ids = $ids ? $ids : $this->request->param("ids");
        if ($ids) {
            $model = model('closeroom');
            if ($this->request->has('params')) {
                parse_str($this->request->post("params"), $values);
                $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
                if ($values) {

                    $count = 0;
                    Db::startTrans();
                    try {
                        $list = $model->where("chid", 'in', $ids)->select();
                        foreach ($list as $index => $item) {
                            $count += $item->isUpdate(true)->save($values);
                        }
                        Db::commit();
                    } catch (PDOException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    if ($count) {
                        $this->success();
                    } else {
                        $this->error(__('No rows were updated'));
                    }
                } else {
                    $this->error(__('You have no permission'));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {

            $data =  db("closeroom")->where(['cid'=>$ids])->field("cid,chid")->find();

            $res = db("closeroom")->where(['chid'=>$data['chid']])->delete();
            if($res){
                $this->success();
            }else{
                $this->error("删除失败");
            }

        }

    }

    /**
     * 添加
     */
    public function add()
    {
        $serviceList = [];
        if ($this->request->isPost()) {
            $model = model('closeroom');
            $params = $this->request->post();

            if ($params) {
                $params = $this->preExcludeFields($params);



                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                $result = false;
                Db::startTrans();

                try {
                    $cetime = $params["row"]['cetime'];
                    $cstime = $params["row"]['cstime'];
                    if($cetime < $cstime){
                        $this->error('结束时间不能小于开始时间');
                    }
                    $hid = $params['row']['chid'];

                    $hotel = db("hotels")->where(['hid'=>$hid])->find();
                    $roomids = $params["row"]['crid'];
                    $len = count($roomids);
                    $alldata = [];
                    for($i=0;$i<$len;$i++){
                        $room = db("house")->where(['id'=>$roomids[$i]])->find();
                        $data['chtitle'] = $hotel['hoteltitle'];
                        $data['chid'] = $hid;
                        $data['crtitle'] = $room['h_title'];
                        $data['crcode'] = $room['h_housebrand'];
                        $data['crid'] = $roomids[$i];
                        $data['ctime'] = date("Y-m-d H:i:s",time());
                        $data['cstime'] =strtotime(date("Y-m-d 00:00:00",strtotime($cstime)));
                        $data['cetime'] = strtotime(date("Y-m-d 23:59:59",strtotime($cetime)));
                        $data['cetime2'] =  strtotime(date("Y-m-d 23:59:59",strtotime("+1 day",strtotime($cetime))));
                        $data['chhtml'] =  json_encode($hotel);
                        $data['crhtml'] =  json_encode($room);
                        $alldata[] = $data;
                    }



                    $result = $model->insertAll($alldata);
                   // $result = $model->save($params["row"]);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{


        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {


        $model = model('closeroom');
        $row = $model->get($ids)->toArray();

        //获取所有房间
        $rooms = db("closeroom")->where(['chid'=>$row['chid']])->field("crid")->select();
        $rids = "";
        foreach ($rooms as $v){
            $rids .= $v['crid'].",";
        }
        if($rids){
            $rids = rtrim($rids,",");
        }
        $row['rids'] = $rids;

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $params = $this->preExcludeFields($params);
                try {
                    if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                        $params[$this->dataLimitField] = $this->auth->id;
                    }

                    $cetime = $params["row"]['cetime'];
                    $cstime = $params["row"]['cstime'];
                    if($cetime < $cstime){
                        $this->error('结束时间不能小于开始时间');
                    }
                    $hid = $params['row']['chid'];
                    //删除原来的酒店数据 重新创建
                    $has = db("closeroom")->where(['chid'=>$hid])->delete();
                    if(!$has){
                        $this->error('数据更新失败');
                    }

                    $hotel = db("hotels")->where(['hid'=>$hid])->find();
                    $roomids = $params["row"]['crid'];
                    $len = count($roomids);
                    $alldata = [];
                    for($i=0;$i<$len;$i++){
                        $room = db("house")->where(['id'=>$roomids[$i]])->find();
                        $data['chtitle'] = $hotel['hoteltitle'];
                        $data['chid'] = $hid;
                        $data['crtitle'] = $room['h_title'];
                        $data['crcode'] = $room['h_housebrand'];
                        $data['crid'] = $roomids[$i];
                        $data['ctime'] = date("Y-m-d H:i:s",time());
                        $data['cstime'] = $cstime;
                        $data['cetime'] =  $cetime;
                        $data['cetime2'] =  date("Y-m-d 12:00:00",strtotime("+1 day",strtotime($cetime)));;
                        $data['chhtml'] =  json_encode($hotel);
                        $data['crhtml'] =  json_encode($room);
                        $alldata[] = $data;
                    }
                    $result = $model->insertAll($alldata);
                    if($result){
                        $this->success("修改成功");
                    }else{
                        $this->error("修改失败");
                    }

                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{

        }


        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * Selectpage搜索
     *
     * @internal
     */
    public function selectpage()
    {
        return parent::selectpage();
    }
}
